package main

import (
	"context"
	"time"

	cert "k8s.io/api/certificates/v1beta1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/watch"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/rest"
	"k8s.io/klog/v2"
)

const ()

func main() {
	ctx := context.Background()
	//log := klogr.Logger.WithValues("csr-controller")

	// creates the in-cluster config
	config, err := rest.InClusterConfig()
	if err != nil {
		klog.Error(err, "Get KubeConfig failed.")
		panic(err.Error())
	}
	// creates the clientset
	clientset, err := kubernetes.NewForConfig(config)
	if err != nil {
		klog.Error(err, "Create KubeClient failed.")
		panic(err.Error())
	}

	csrw, err := clientset.CertificatesV1beta1().CertificateSigningRequests().Watch(ctx, metav1.ListOptions{})
	if err != nil {
		klog.Error(err, "CSR watch failed.")
		panic(err.Error())
	}
	//defer close(csrw.ResultChan())

	for {
		select {
		case event, ok := <-csrw.ResultChan():
			if !ok {
				klog.Warning("!!!!!csrwatch chan has been close!!!!")
				klog.Info("clean chan over!")
				time.Sleep(time.Second * 5)
			}
			switch event.Type {
			case watch.Added:
				csr, ok := event.Object.(*cert.CertificateSigningRequest)
				if !ok {
					klog.Error("Reverse failed.")
				}
				if *csr.Spec.SignerName == cert.KubeletServingSignerName {
					_, err := clientset.CertificatesV1beta1().CertificateSigningRequests().UpdateApproval(ctx, csr, metav1.UpdateOptions{})
					if err != nil {
						klog.Error(err, "CSR Approved failed.")
					} else {
						klog.V(2).Infof("%s Approved.", csr.Name)
					}
				}
			}
		}
	}

}
